import React from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Form, Button, Select, Checkbox, TimePicker, message, Spin } from 'antd';
import moment from 'moment';
import { FormInstance } from 'antd/lib/form';
import FirstOrgListComponent from './components/FirstOrgListComponent';
import { getPublishTimeSetup, publishTimeSetup } from './service';
import { setupItem } from './data.d';

const { Option } = Select;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 10 },
};
const tailLayout = {
  wrapperCol: { offset: 4, span: 10 },
};

const options = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 },
];

let startTime = "";

class publishComponent extends React.Component {
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    this.state = {
      loading:false,
      loading1:false,
      setupInfo:{
        "topOrgId":null,
        "startTime":"",
        "type":"day",
        "daysOfWeek":[1,2,3,4,5,6,7],
      },
      daysList:[], //每周
    }
  }

  componentDidMount(){
    const user = localStorage.getItem("user");
    this.setState({loading1:true})
    if(user){
      const topOrgId = JSON.parse(user).topOrgId;
      const obj = new Object;
      obj["topOrgId"] = topOrgId;
      const data = Object.assign({}, this.state.setupInfo, { topOrgId: topOrgId });
      this.setState({setupInfo:JSON.parse(JSON.stringify(data))});
      this.formRef.current?.setFieldsValue(this.state.setupInfo);
      new Promise((resolve, reject) => {
        getPublishTimeSetup(obj)
          .then((res) => {
            if (res && res.code === 200) {
              const data = res.data;
              console.log(data)
              if(data && data.startTime){
                const setupInfoObj = new Object();
                setupInfoObj["topOrgId"] = topOrgId;
                setupInfoObj["startTime"] = moment(data.startTime, "HH:mm:ss");
                startTime = data.startTime;
                const days = data.daysOfWeek;
                if(days.length == 7){
                  setupInfoObj["type"] = "day";
                }else{
                  setupInfoObj["type"] = "week";
                }
                setupInfoObj["daysOfWeek"] = data.daysOfWeek;
                this.setState({setupInfo:setupInfoObj});
              }
              this.formRef.current?.setFieldsValue(this.state.setupInfo);
              this.formRef.current?.resetFields();
              resolve(true);
            } else {
              message.error('请求失败');
              resolve(false);
            }
            this.setState({loading1:false});
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  }

  onChange = (time, timeString) =>{
    startTime = timeString;
  }

  onFinish = (values:setupItem) => {
    this.setState({loading:true});
    values.startTime = startTime;
    const obj = new Object;
    const type = values.type;
    if(type == "week"){
      obj["daysOfWeek"] = values.week.toString();
    }else{
      obj["daysOfWeek"] = "1,2,3,4,5,6,7";
    }
    obj["startTime"] = startTime;
    obj["topOrgId"] = this.state.setupInfo.topOrgId;

    new Promise((resolve, reject) => {
      publishTimeSetup(obj)
        .then((res) => {
          if (res.code === 200) {
            message.success('设置成功');
            resolve(true);
          } else {
            message.error('请求失败，'+res.message);
            resolve(false);
          }
          this.setState({loading:false});
        })
        .catch((error) => {
          message.error('请求失败');
          this.setState({loading:false});
          reject(error);
        });
    });
    
  };

  onReset = () => {
    this.formRef.current?.resetFields();
  };

  weekSelectChange = () => {
    this.formRef.current?.validateFields();
  }

  onTypeChange = (type:string) =>{ //循环周期select
    this.setState({daysList:[]});
    if(type == "week"){
      this.formRef.current?.setFieldsValue({week:[]});
    }
  }
  
  render() {
    return (
      <PageContainer>
        <Spin spinning={this.state.loading1}>
          <Form {...layout} ref={this.formRef} initialValues={this.state.setupInfo} onFinish={this.onFinish}>
            <Form.Item 
              name="topOrgId" 
              label="所属机构" 
              rules={[{ required: true }]}
              >
                <FirstOrgListComponent 
                    disabled={false}
                    init={true}
                    defaultvalue={this.state.setupInfo.topOrgId} 
                    selectChange={(value) => {
                      this.formRef.current?.setFieldsValue({topOrgId:value});
                    }}>
                </FirstOrgListComponent>
              </Form.Item>
              <Form.Item 
                name="startTime" 
                label="开始时间"
                rules={[{ required: true }]}
              >
                <TimePicker style={{width:200}} onChange={this.onChange} />
              </Form.Item>
              <Form.Item 
              name="type" 
              label="循环周期" 
              rules={[{ required: true }, {
                  validator: (rule, value, callback) => {
                    if(value === "week" && 
                      (this.formRef.current?.getFieldValue('week') == undefined
                      || this.formRef.current?.getFieldValue('week').length == 0)
                    ){
                        callback("请选择循环周期");
                    }else{
                      callback();
                    }
                  },
              },]}>
              <Select defaultValue="day"  onChange={this.onTypeChange} style={{width:200}}>
                <Option value="day">每天</Option>
                <Option value="week">每周</Option>
              </Select>
            </Form.Item>
            <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) =>
                prevValues.type !== currentValues.type
                }   
            >
            {({ getFieldValue }) => {
                return getFieldValue('type') === "week" ? (
                <Form.Item 
                  label=" " 
                  colon={false} 
                  name="week" 
                  initialValue={(this.state.setupInfo)?this.state.setupInfo.daysOfWeek:[]}
                >
                    <Checkbox.Group options={options} onChange={this.weekSelectChange} />
                </Form.Item>
                ) : null;
            }}
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit" loading={this.state.loading}>
                保存
              </Button>
              <Button htmlType="button" onClick={this.onReset} style={{ marginLeft: 10 }}>
                重置
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </PageContainer>
    );
  }
}
export default publishComponent;
